﻿using System;
using mojoPortal.Web;
using Resources;
using ud_SwirlingQuestion.Business;
using mojoPortal.Web.Framework;
using ud_Utilities;
using System.Collections;
using mojoPortal.Business;

namespace ud_SwirlingQuestion
{
    public partial class PostQuestionPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Guid itemGuid = Guid.Empty;
        protected Double timeOffset;
        private TimeZoneInfo timeZone;
        SwirlingQuestionConfiguration config = new SwirlingQuestionConfiguration();
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string DeleteLinkText = SwirlingQuestionResource.ButtonDelete;
        protected string DeleteLinkImageUrl = string.Empty;
        protected string EditLinkText = SwirlingQuestionResource.ButtonEdit;
        protected string EditLinkImageUrl = string.Empty;
        readonly DBSwirlingQuestion repository = new DBSwirlingQuestion();
        ud_QA item = new ud_QA();
        private readonly SiteUser user = SiteUtils.GetCurrentSiteUser();

        void Page_Load(object sender, EventArgs e)
        {
            Page.EnableViewState = true;
            SetupScripts();
            if (!Page.IsPostBack)
            {
                LoadSettings();
                PopulateLabels();
            }
            PopulateControls();
        }

        private void PopulateControls()
        {
            BindEdit();
        }

        private void BindEdit()
        {
            if (Page.IsPostBack) return;
            if (itemGuid.Equals(Guid.Empty)) return;
            item = repository.GetOne(itemGuid);
            if (item == null) return;
            txtItemUrl.Text = item.ItemUrl;
            txtCreatedPhone.Text = item.CreatedByPhone;
            txtCreatedName.Text = item.CreatedByName;
            txtCreatedEmail.Text = item.CreatedByEmail;
            txtQuestion.Text = item.Question;
            txtTitle.Text = item.Title;
            hdnQuestion.Value = txtTitle.Text;
        }

        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            mp1.CssClass += config.CustomCssClass;
        }

        private void PopulateLabels()
        {
            PageTitle = SiteUtils.FormatPageTitle(siteSettings, SwirlingQuestionResource.SwirlingQuestionEditPage);
            moduleTitle.Header = SwirlingQuestionResource.SwirlingQuestionEditPage;
            btnBack.Text = SwirlingQuestionResource.ButtonBack;
            btnDelete.Text = SwirlingQuestionResource.ButtonDelete;
            btnSave.Text = SwirlingQuestionResource.ButtonSave;
            EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
            DeleteLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
            if (itemGuid.Equals(Guid.Empty))
            {
                btnDelete.Visible = false;
            }
            Utilities.AddConfirmButton(btnDelete, SwirlingQuestionResource.DeleteConfirmWarning);
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            repository.Delete(itemGuid);
            Refresh();
        }

        void btnBack_Click(object sender, EventArgs e)
        {
            WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (!captcha.IsValid)
            {
                lblError.Text = SwirlingQuestionResource.WrongAnswer;
                updatePanelMessage.Update();
                return;
            }
            string itemURL = string.Empty;
            Guid tempGuid = Guid.Empty;
            item = repository.GetOne(itemGuid);
            if (item != null)
            {
                itemURL = item.ItemUrl;
                tempGuid = item.Guid;
            }
            if (txtItemUrl.Text.Length == 0)
            {
                txtItemUrl.Text = SuggestUrl();
            }
            String friendlyUrlString = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", String.Empty));
            FriendlyUrl friendlyUrl = new FriendlyUrl(siteSettings.SiteId, friendlyUrlString);

            if (
                ((friendlyUrl.FoundFriendlyUrl) && (friendlyUrl.PageGuid != tempGuid))
                && (itemURL != txtItemUrl.Text)
                )
            {
                lblError.Text = SwirlingQuestionResource.PageUrlInUseBlogErrorMessage;
                return;
            }

            if (!friendlyUrl.FoundFriendlyUrl)
            {
                if (WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString))
                {
                    lblError.Text = SwirlingQuestionResource.PageUrlInUseBlogErrorMessage;
                    return;
                }
            }
            string oldUrl = itemURL.Replace("~/", string.Empty);
            string newUrl = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", string.Empty));
            txtItemUrl.Text = @"~/" + newUrl;
            int userID = user == null ? 0 : user.UserId;
            if (itemGuid.Equals(Guid.Empty))
            {
                repository.Create(moduleId, txtTitle.Text, txtQuestion.Text, string.Empty, false, txtCreatedName.Text, txtCreatedEmail.Text, txtCreatedPhone.Text, userID, txtItemUrl.Text, false, out itemGuid);
            }
            else
            {
                repository.Update(itemGuid, txtTitle.Text, txtQuestion.Text, string.Empty, false, txtCreatedName.Text, txtCreatedEmail.Text, txtCreatedPhone.Text, userID, txtItemUrl.Text, false);
            }
            item = repository.GetOne(itemGuid);
            if (!friendlyUrl.FoundFriendlyUrl)
            {
                if ((friendlyUrlString.Length > 0) && (!WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString)))
                {
                    FriendlyUrl newFriendlyUrl = new FriendlyUrl
                    {
                        SiteId = siteSettings.SiteId,
                        SiteGuid = siteSettings.SiteGuid,
                        PageGuid = item.Guid,
                        Url = friendlyUrlString,
                        RealUrl = "~/SwirlingQuestion/ViewAnswer.aspx?pageid="
                                  + pageId.ToInvariantString()
                                  + "&mid=" + moduleId.ToInvariantString()
                                  + "&item=" + item.Guid
                    };

                    newFriendlyUrl.Save();
                }

                //if post was renamed url will change, if url changes we need to redirect from the old url to the new with 301
                if ((oldUrl.Length > 0) && (newUrl.Length > 0) && (!SiteUtils.UrlsMatch(oldUrl, newUrl)))
                {
                    //worry about the risk of a redirect loop if the page is restored to the old url again
                    // don't create it if a redirect for the new url exists
                    if (
                        (!RedirectInfo.Exists(siteSettings.SiteId, oldUrl))
                        && (!RedirectInfo.Exists(siteSettings.SiteId, newUrl))
                        )
                    {
                        RedirectInfo redirect = new RedirectInfo
                        {
                            SiteGuid = siteSettings.SiteGuid,
                            SiteId = siteSettings.SiteId,
                            OldUrl = oldUrl,
                            NewUrl = newUrl
                        };
                        redirect.Save();
                    }
                    // since we have created a redirect we don't need the old friendly url
                    FriendlyUrl oldFriendlyUrl = new FriendlyUrl(siteSettings.SiteId, oldUrl);
                    if ((oldFriendlyUrl.FoundFriendlyUrl) && (oldFriendlyUrl.PageGuid == item.Guid))
                    {
                        FriendlyUrl.DeleteUrl(oldFriendlyUrl.UrlId);
                    }

                }
            }

            Refresh();
        }

        private string SuggestUrl()
        {
            string pageName = txtTitle.Text;
            if (WebConfigSettings.AppendDateToBlogUrls)
            {
                if (timeZone != null)
                {
                    pageName += "-" + DateTime.UtcNow.ToLocalTime(timeZone).ToString("yyyy-MM-dd");
                }
                else
                {
                    pageName += "-" + DateTime.UtcNow.AddHours(timeOffset).ToString("yyyy-MM-dd");
                }

            }
            return SiteUtils.SuggestFriendlyUrl(pageName, siteSettings);
        }

        private void Refresh()
        {
            WebUtils.SetupRedirect(this, SiteRoot + "/SwirlingQuestion/Finish.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
        }

        private void SetupScripts()
        {
            if (!Page.ClientScript.IsClientScriptBlockRegistered("sarissa"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "sarissa", "<script src=\""
                    + ResolveUrl("~/ClientScript/sarissa/sarissa.js") + "\" type=\"text/javascript\"></script>");
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("sarissa_ieemu_xpath"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "sarissa_ieemu_xpath", "<script src=\""
                    + ResolveUrl("~/ClientScript/sarissa/sarissa_ieemu_xpath.js") + "\" type=\"text/javascript\"></script>");
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered("friendlyurlsuggest"))
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "friendlyurlsuggest", "<script src=\""
                    + ResolveUrl("~/ClientScript/friendlyurlsuggest_v2.js") + "\" type=\"text/javascript\"></script>");
            }

            string focusScript = string.Empty;
            if (itemGuid == Guid.Empty) { focusScript = "document.getElementById('" + txtTitle.ClientID + "').focus();"; }

            string hookupInputScript = "<script type=\"text/javascript\">"
                + "new UrlHelper( "
                + "document.getElementById('" + txtTitle.ClientID + "'),  "
                + "document.getElementById('" + txtItemUrl.ClientID + "'), "
                + "document.getElementById('" + hdnQuestion.ClientID + "'), "
                + "document.getElementById('" + spnUrlWarning.ClientID + "'), "
                + "\"" + SiteRoot + "/Article/BlogUrlSuggestService.ashx" + "\""
                + "); " + focusScript + "</script>";

            if (!Page.ClientScript.IsStartupScriptRegistered(UniqueID + "urlscript"))
            {
                Page.ClientScript.RegisterStartupScript(
                    GetType(),
                    UniqueID + "urlscript", hookupInputScript);
            }
        }

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
            Load += Page_Load;
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            SuppressPageMenu();
            btnSave.Click += btnSave_Click;
            btnBack.Click += btnBack_Click;
            btnDelete.Click += btnDelete_Click;
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);
            itemGuid = WebUtils.ParseGuidFromQueryString("itemid", itemGuid);

        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new SwirlingQuestionConfiguration(settings);
            LoadSideContent(config.ShowLeftPanelSetting, config.ShowRightPanelSetting, config.ShowTopPanelSetting,
                            config.ShowBottomPanelSetting, config.ShowNumberModuleSetting);
        }

        #endregion
    }
}